package services

import (
	"encoding/json"
	"os"
	"time"

	"homepage-backend/internal/models"
)

// LoadAnnouncements 从文件加载公告数据
func LoadAnnouncements(filePath string) ([]models.Announcement, error) {
	file, err := os.ReadFile(filePath)
	if err != nil {
		return nil, err
	}

	var announcements []models.Announcement
	if err := json.Unmarshal(file, &announcements); err != nil {
		return nil, err
	}

	return announcements, nil
}

// AddAnnouncement 添加新公告
func AddAnnouncement(filePath string, ann models.Announcement) error {
	list, err := LoadAnnouncements(filePath)
	if err != nil {
		return err
	}
	// 自动生成唯一ID
	ann.ID = GenerateShortID(ann.Content + ann.Publisher + time.Now().String())
	ann.PublishTime = time.Now()
	list = append(list, ann)
	return saveAnnouncements(filePath, list)
}

// UpdateAnnouncement 修改公告（按ID匹配，保留原有publishTime）
func UpdateAnnouncement(filePath string, ann models.Announcement) error {
	list, err := LoadAnnouncements(filePath)
	if err != nil {
		return err
	}
	for i, a := range list {
		if a.ID == ann.ID {
			ann.PublishTime = a.PublishTime // 保留原有时间
			list[i] = ann
			return saveAnnouncements(filePath, list)
		}
	}
	return nil
}

// DeleteAnnouncement 删除公告（按ID匹配）
func DeleteAnnouncement(filePath string, id string) error {
	list, err := LoadAnnouncements(filePath)
	if err != nil {
		return err
	}
	newList := make([]models.Announcement, 0, len(list))
	for _, a := range list {
		if a.ID != id {
			newList = append(newList, a)
		}
	}
	return saveAnnouncements(filePath, newList)
}

// saveAnnouncements 保存公告数据到文件
func saveAnnouncements(filePath string, list []models.Announcement) error {
	data, err := json.MarshalIndent(list, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(filePath, data, 0644)
}

// mapToAnnouncement 辅助函数
func mapToAnnouncement(m map[string]interface{}) models.Announcement {
	ann := models.Announcement{}
	if v, ok := m["content"].(string); ok {
		ann.Content = v
	}
	if v, ok := m["publisher"].(string); ok {
		ann.Publisher = v
	}
	if v, ok := m["importance"].(float64); ok {
		ann.Importance = int(v)
	}
	ann.PublishTime = time.Now()
	return ann
}
